<template>
  <div class="message-box">
    <div class="message">
      <el-container>
        <el-aside width="200px" >
          <MessageNavBar></MessageNavBar>
        </el-aside>
        <el-main style="height: 650px;">
          <router-view></router-view>
        </el-main>
      </el-container>
    </div>
  </div>
</template>
<script setup>
import MessageNavBar from "@/components/navbar/MessageNavBar.vue";
import {nextTick, onMounted, onUnmounted, ref} from "vue";
import emitter from "@/utils/emitter.js";
import {getChatterList} from "@/api/api.js";
onMounted(()=>{
  emitter.emit("isMessagePage",true)
  const userId = localStorage.getItem("userId");
  // const ws = new WebSocket(`ws://localhost:8080/message/notice/${userId}`);
  // initWebSocket(ws);
})


function initWebSocket(websocket){
  websocket.onerror = function(event){
    console.log("WebSocket error")
  }

  websocket.onopen = function(event){
    console.log("WebSocket open")
  }

  websocket.onmessage = async function(event){
    console.log(event.data)
    const data = JSON.parse(event.data)
    console.log(data)
    const obj = {
      id:currentRecordList.value.length + 1,
      senderId:12,
      receiverId:13,
      content:event.data,
      createTime:"2023-05-17 12:00"
    }
    console.log("当前聊天者id："+currentChatter.value.chatterId)
    if(data.receiverId !== currentChatter.value.chatterId){
      // 重新获取所有数据
      const res = await getChatterList(1,(pageParams.page-1)*pageParams.pageSize);
      chatterList.value = res.data.records
    }else{
      currentRecordList.value.push(data)
    }

    console.log("WebSocket message")
    await nextTick(() => {
      scrollToBottom()
    })
  }

  websocket.onclose = function(event){
    console.log("WebSocket close")
  }
  websocket.onbeforeunload = function(event){
    websocket.close()
  }

}
onUnmounted(()=>{
  emitter.emit("isMessagePage",false)
})
</script>
<style scoped lang="scss">
.message-box{
  //background: url("/message-bg.jpeg");
  background: url("/banner06.webp");
  //background-size: cover;
  height: 650px;
}
.message{
  width: 1200px;
  margin: 0 auto;

}
.el-main{
  padding: 0;
  height: 650px;
}
</style>